<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="当事人名称" prop="partyName">
        <el-input
          v-model="queryParams.partyName"
          placeholder="请输入当事人名称"
          clearable
          :style="{
            width: '220px',
          }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="立案号" prop="caseNo">
        <el-input
          v-model="queryParams.caseNo"
          placeholder="请输入立案号"
          clearable
          :style="{
            width: '220px',
          }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="行政处罚决定书文号" prop="decisionsNo" class="long-label">
        <el-input
          v-model="queryParams.decisionsNo"
          placeholder="请输入行政处罚决定书文号"
          clearable
          :style="{
            width: '220px',
          }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="登记时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :style="{
            width: '220px',
          }"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['penaltydecisions:penaltydecisions:add']">
          新增
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['penaltydecisions:penaltydecisions:edit']">
          修改
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['penaltydecisions:penaltydecisions:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          :disabled="!multiple2 && multiple"
          @click="handleExport(1)"
          v-hasPermi="['penaltydecisions:penaltydecisions:export']">
          导出送达回证
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          :disabled="multiple"
          @click="handleExport(2)"
          v-hasPermi="['penaltydecisions:penaltydecisions:export']">
          导出处罚决定书
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="penaltydecisionsList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="column in newColumns" :key="column.key">
        <el-table-column
          :label="column.label"
          :prop="column.key"
          :min-width="column.minWidth || ''"
          :width="column.width || ''">
          <template #default="scope" v-if="column.key === 'createTime'">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </template>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="240"
        :show-overflow-tooltip="false"
        fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="view"
            @click="handleUpdate(scope.row, 'view')"
            v-hasPermi="['penaltydecisions:penaltydecisions:query']">
            查看
          </el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row, 'edit')"
            v-hasPermi="['penaltydecisions:penaltydecisions:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="view" @click="handlePreview(scope.row)">预览</el-button>
          <el-button link type="primary" icon="upload" @click="handleUpload(scope.row)">上传附件</el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['penaltydecisions:penaltydecisions:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改处罚决定书对话框 -->
    <el-dialog v-if="open" :title="title" v-model="open" width="1200px" append-to-body>
      <el-form
        ref="penaltydecisionsRef"
        :model="form"
        :rules="rules"
        :disabled="title === '查看处罚决定书'"
        label-width="138px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="立案号" prop="caseId">
              <el-select v-model="form.caseId" placeholder="请选择立案号" clearable @change="handleCase">
                <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当事人名称" prop="partyName">
              <el-input v-model="form.partyName" disabled placeholder="请输入当事人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法定代表人" prop="legalRepresentative">
              <el-input v-model="form.legalRepresentative" disabled placeholder="请输入法定代表人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="营业执照类型" prop="businessType">
              <el-input v-model="form.businessType" disabled placeholder="请输入营业执照类型" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-model="form.creditCode" disabled placeholder="请输入统一社会信用代码" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="地址" :rules="rules.addressObj" prop="addressObj">
              <locationSelect v-model="form.addressObj" disabled style="width: 100%" />
            </el-form-item>
          </el-col>
          <CaseSituation
            v-if="cutShowCaseSituation"
            ref="caseSituationRef"
            v-model="form"
            :show="'案情说明,证据证明,违反条例,陈述申辩,处理依据'"
            :disabled="title === '查看处罚决定书'"
            :caseIsEdit="setCaseIsEdit"
            :stateIsEdit="setCaseIsEdit"
            :violationIsEdit="true" />
          <el-col
            v-if="form.caseProcedure === '1' || (['2', '3'].includes(form.caseProcedure) && form.needPenalty === '1')"
            :span="24">
            <el-form-item label="缴纳罚款告知" prop="paymentNotice">
              <el-input v-model="form.paymentNotice" :rows="4" type="textarea" placeholder="请输入缴纳罚款告知" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="行政复议/诉讼告知" prop="litigationNotice">
              <el-input
                v-model="form.litigationNotice"
                :rows="4"
                type="textarea"
                placeholder="请输入行政复议/诉讼告知" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="title !== '查看处罚决定书'" type="primary" @click="submitForm">提 交</el-button>
          <el-button :loading="preViewLoading" @click="handlePreview2">预览</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传附件弹窗 -->
    <el-dialog title="上传附件" v-model="fileModal" width="1200px">
      <FileList v-if="fileModal" :fileUploadList="fileUploadList" />
      <template #footer>
        <div class="form-footer">
          <el-button type="primary" @click="handleUploadConfirm">保存</el-button>
          <el-button @click="() => (fileModal = false)">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Penaltydecisions">
import { useRoute } from 'vue-router'
import {
  listPenaltydecisions,
  getPenaltydecisions,
  delPenaltydecisions,
  addPenaltydecisions,
  updatePenaltydecisions,
  previewPenaltydecisions,
  addPenaltydecisionsFiles,
  getCaseList,
  exportPenaltydecisions,
  previewInquiryPdf,
} from '@/api/caseHandling/administrativePenalty'
import { registrationcaseDetail, penaltydecisionsGetContent } from '@/api/filingReview/register'
import locationSelect from '@/components/locationSelect/index.vue'
import FileList from '@/components/FileList/index.vue'
import { ElMessage } from 'element-plus'
import { downloadBlob } from '@/utils/download.js'
import CaseSituation from '@/components/CaseSituation/index.vue'

const { proxy } = getCurrentInstance()

const route = useRoute()

const query = route.query
if (query.formId) {
  // 案件检索跳转过来
  proxy.$nextTick(() => {
    setTimeout(() => {
      handleUpdate({ id: query.formId }, 'view')
    }, 100)
  })
}

const penaltydecisionsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const multiple2 = ref(false)
const total = ref(0)
const title = ref('')
const daterangeCreateTime = ref([])

const columns = ref([
  { key: 'name', label: '文书名称', visible: true, minWidth: '180' },
  { key: 'decisionsNo', label: '行政处罚决定书文号', visible: true, minWidth: '220' },
  { key: 'caseNo', label: '立案号', visible: true, minWidth: '220' },
  { key: 'partyName', label: '当事人名称', visible: true, minWidth: '180' },
  { key: 'createTime', label: '登记时间', visible: true, width: '180' },
])
const newColumns = computed(() => {
  return columns.value.filter(column => column.visible)
})
// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule, value, callback) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择拍摄地点'))
  } else {
    callback()
  }
}
const data = reactive({
  form: {
    caseDesc: undefined,
    caseDesc1: undefined,
    caseDesc2: undefined,
    caseDesc3: undefined,
    content1: undefined,
    content2: undefined,
    evidenceDesc: undefined,
    violationRegulations: undefined,
    statementDefense: undefined,
    statementDefense1: undefined,
    statementDefense2: undefined,
    statementDefense3: undefined,
    statementDefense4: undefined,
    statementDefense5: undefined,
    handlingBasis: undefined,
    paymentNotice: undefined,
    litigationNotice: undefined,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    caseId: undefined,
    partyName: undefined,
    partyId: undefined,
    createTime: undefined,
    businessType: undefined,
    creditCode: undefined,
    legalRepresentative: undefined,
  },
  rules: {
    caseId: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
    createTime: [{ required: true, message: '立案时间不能为空', trigger: ['blur', 'change'] }],
    partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
    addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
    businessType: [{ required: true, message: '营业执照类型不能为空', trigger: 'change' }],
    creditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: ['blur', 'change'] }],
    legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
    caseDesc: [{ required: true, message: '请输入案情说明', trigger: ['blur', 'change'] }],
    evidenceDesc: [{ required: true, message: '请输入证据证明', trigger: ['blur', 'change'] }],
    violationRegulations: [{ required: true, message: '请输入违反条例', trigger: ['blur', 'change'] }],
    statementDefense: [{ required: true, message: '请输入陈述申辩', trigger: ['blur', 'change'] }],
    handlingBasis: [{ required: true, message: '请输入处理依据', trigger: ['blur', 'change'] }],
    paymentNotice: [{ required: true, message: '请输入缴纳罚款告知', trigger: ['blur', 'change'] }],
    litigationNotice: [{ required: true, message: '请输入行政复议/诉讼告知', trigger: ['blur', 'change'] }],
  },
})

const { queryParams, form, rules } = toRefs(data)
const caseSituationRef = ref(null)

const setCaseIsEdit = computed(() => {
  if (form.value.caseProcedure === '1') {
    // 简易案件
    return title.value === '添加处罚决定书' ? false : true
  } else if (['2', '3'].includes(form.value.caseProcedure)) {
    // 一般案件 / 重大案件
    return true
  }
})

/** 查询处罚决定书列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params['beginCreateTime'] = daterangeCreateTime.value[0]
    queryParams.value.params['endCreateTime'] = daterangeCreateTime.value[1]
  }
  listPenaltydecisions(queryParams.value).then(response => {
    penaltydecisionsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    caseId: undefined,
    createTime: undefined,
    partyName: undefined,
    partyId: undefined,
    createTime: undefined,
    businessType: undefined,
    creditCode: undefined,
    legalRepresentative: undefined,
    caseDesc: undefined,
    caseDesc1: undefined,
    caseDesc2: undefined,
    caseDesc3: undefined,
    content1: undefined,
    content2: undefined,
    evidenceDesc: undefined,
    violationRegulations: undefined,
    statementDefense: undefined,
    statementDefense1: undefined,
    statementDefense2: undefined,
    statementDefense3: undefined,
    statementDefense4: undefined,
    statementDefense5: undefined,
    handlingBasis: undefined,
    paymentNotice: undefined,
    litigationNotice: '',
  }
  proxy.resetForm('penaltydecisionsRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
  let num = 0
  selection.forEach(item => {
    if (item.caseProcedure === '1') {
      num++
    }
  })
  multiple2.value = num !== 0
}
const numberList = ref([])
const handleCaseList = async () => {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}
const cutShowCaseSituation = ref(true)
const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    cutShowCaseSituation.value = false
    form.value.partyName = undefined
    form.value.partyId = undefined
    form.value.legalRepresentative = undefined
    form.value.businessType = undefined
    form.value.creditCode = undefined
    form.value.paymentNotice = undefined
    form.value.litigationNotice = undefined
    // form.value.needPenalty === '1'
    //   ? '限在接到本处罚决定书之日起十五日内持《北京市非税收入缴款通知单》以柜面缴费或网上缴费的方式缴纳罚款。如确有经济困难，可以自收到本处罚决定书后向本行政机关申请延期或者分期缴纳罚款。逾期不缴纳罚款的，本机关将依据《中华人民共和国行政处罚法》第七十二条第一款第一项的规定，每日将按罚款数额的百分之三加处罚款。依据《北京市优化营商环境条例》第七十三条和《北京市公共信用信息管理办法》第十条第一款第三项的规定，本行政机关将对本行政处罚信息进行公示并纳入公共信用信息服务平台。'
    //   : undefined
    form.value.addressObj = {
      photoLocation: undefined,
      streetOfPhotoLocation: undefined,
    }
    if (!val) {
      return
    }
    const res = await registrationcaseDetail(val)
    const {
      partyName,
      partyId,
      legalRepresentative,
      businessType,
      unifiedSocialCreditCode,
      streetOfCompanyAddress,
      address,
    } = res.data
    form.value.partyName = partyName
    form.value.partyId = partyId
    form.value.legalRepresentative = legalRepresentative
    form.value.businessType = businessType
    form.value.creditCode = unifiedSocialCreditCode
    form.value.caseProcedure = res.data.caseProcedure
    form.value.addressObj = {
      photoLocation: address,
      streetOfPhotoLocation: streetOfCompanyAddress,
    }

    const res2 = await penaltydecisionsGetContent(val)
    // 案情说明不要复核框了，都从后端带
    form.value.caseDesc = res2.data.caseDesc
    if (['2', '3'].includes(form.value.caseProcedure)) {
      // 一般案件 / 重大案件
      form.value.evidenceDesc = res2.data.evidenceDesc
      form.value.violationRegulations = res2.data.violationRegulations
      form.value.statementDefense = res2.data.statementDefense
      form.value.handlingBasis = res2.data.handlingBasis
      form.value.needPenalty = res2.data.needPenalty
      form.value.paymentNotice = res2.data.paymentNotice
      form.value.litigationNotice = res2.data.litigationNotice
      cutShowCaseSituation.value = true
    } else if (form.value.caseProcedure === '1') {
      // 简易案件不需要带出
      if (title.value === '添加处罚决定书') {
        form.value.evidenceDesc = undefined
        form.value.violationRegulations = undefined
        form.value.statementDefense = undefined
        form.value.handlingBasis = undefined
        form.value.needPenalty = undefined
      }
      cutShowCaseSituation.value = true

      setTimeout(() => {
        caseSituationRef.value.handleInitInputs()
      }, 0)
    }

    // setTimeout(() => {
    //   if (title.value === '添加处罚决定书') {
    //     caseSituationRef.value.pullCaseDesc()
    //   }
    //   caseSituationRef.value.handleTextChange()
    // }, 100)
    resolve()
  })
}
/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加处罚决定书'
  handleCaseList()
  nextTick(() => {
    caseSituationRef.value.handleInitInputs()
  })
}
/** 修改按钮操作 */
function handleUpdate(row, type) {
  reset()
  const _id = row.id || ids.value
  getPenaltydecisions(_id).then(response => {
    form.value = response.data
    handleCaseList()
    nextTick(async () => {
      console.log('form', form.value)
      // await handleCase(form.value.caseId)
      form.value.addressObj = {
        photoLocation: form.value.address,
        streetOfPhotoLocation: form.value.streetOfCompanyAddress,
      }
      open.value = true
      title.value = type === 'view' ? '查看处罚决定书' : '修改处罚决定书'
    })
  })
}

// 预览
const previewRow = ref(null)
const handlePreview = async row => {
  loading.value = true
  previewRow.value = row
  const res = await previewPenaltydecisions(row.id)
  if (!!res.msg) {
    window.open(res.msg)
  } else {
    ElMessage.warning('预览文件不存在')
  }
  loading.value = false
}
// 上传附件
const fileModal = ref(false)
const fileUploadList = ref([])
const rowId = ref('')
const handleUpload = async row => {
  rowId.value = row.id
  const res = await getPenaltydecisions(row.id)
  fileUploadList.value = res.data.tpenaltyDecisionsFilesList || []
  fileModal.value = true
}
// 上传附件
const handleUploadConfirm = async () => {
  await addPenaltydecisionsFiles({ id: rowId.value, tpenaltyDecisionsFilesList: fileUploadList.value })
  ElMessage.success('保存成功')
  fileModal.value = false
}

/** 预览 */
const preViewLoading = ref(false)
const handlePreview2 = () => {
  preViewLoading.value = true
  submitForm(true)
    .then(async params => {
      const res = await previewInquiryPdf(params)
      if (!!res.msg) {
        window.open(res.msg)
      } else {
        ElMessage.warning('预览文件不存在')
      }
      preViewLoading.value = false
    })
    .catch(() => {
      preViewLoading.value = false
    })
}

/** 提交按钮 */
function submitForm(isPreview = false) {
  return new Promise((resolve, reject) => {
    let num = 0
    caseSituationRef.value.caseDescSegments.forEach(item => {
      if (item.type === 'input' && !item.value) {
        num += 1
      }
    })
    if (num > 0) {
      ElMessage.error('请将案情说明填写完整')
      reject(false)
      return false
    }
    caseSituationRef.value.statementDefenseSegments.forEach(item => {
      if (item.type === 'input' && !item.value) {
        num += 1
      }
    })
    if (num > 0) {
      ElMessage.error('请将陈述申辩填写完整')
      reject(false)
      return false
    }
    proxy.$refs['penaltydecisionsRef'].validate(valid => {
      if (valid) {
        form.value.address = form.value.addressObj.photoLocation
        form.value.streetOfCompanyAddress = form.value.addressObj.streetOfPhotoLocation
        if (isPreview === true) {
          resolve(form.value)
          return
        }
        if (form.value.id != null) {
          updatePenaltydecisions(form.value).then(response => {
            proxy.$modal.msgSuccess('修改成功')
            open.value = false
            getList()
          })
        } else {
          addPenaltydecisions(form.value).then(response => {
            proxy.$modal.msgSuccess('新增成功')
            open.value = false
            getList()
          })
        }
      } else {
        reject(false)
      }
    })
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确定删除处罚决定书编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delPenaltydecisions(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
async function handleExport(type) {
  const _ids = ids.value
  if (type === 2) {
    const res = await exportPenaltydecisions(_ids)
    downloadBlob(res)
  }
}
getList()
</script>

<style scoped lang="scss"></style>
